<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="../vue.js"></script>
  </head>

  <body>
    <div id="app">
      <button @click="count++">修改count</button>
      <button @click="unWatch">取消</button>
      <p>{{count}}</p>
    </div>
    <script>
      Vue.config.productionTip = false;

      const vm = new Vue({
        el: "#app",
        data() {
          return {
            count: 0,
          };
        },
        methods: {
          /* 
            临时存放一个回调函数给unWacth,在将来$watch监听后，把返回取消监听函数赋值过来
          */
          unWatch: () => {},
        },
      });

      //使用$watch可以在外部书写监听
      //$watch返回一个unWatch的方法，用来取消当前的监听
      vm.unWatch = vm.$watch(
        "count",
        function () {
          console.log("count改变了");
          console.log(this);
        },
        {
          deep: true,
          immediate: true,
        }
      );
    </script>
  </body>
</html>
